package nafos.security.auth

import nafos.server.BizException
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *@ClassName SecurityControllerInterceptor
 *@Description TODO
 *@Author hxy
 *@Date 2020/3/11 14:20
 */
abstract class SecurityInterceptor : HandlerInterceptor {

    private var allowHeaders: String = "Content-Type,Origin,Accept,nafosCookie"

    private var exposeHeaders: String = "content-type,nafosCookie,Content-Disposition,Set-Cookie,Cookie"

    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        //处理跨域问题
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"))
        response.setHeader("Access-Control-Allow-Credentials", "true")
        response.addHeader("Access-Control-Expose-Headers", exposeHeaders)
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS" == request.method) {
            response.addHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS")
            response.addHeader("Access-Control-Max-Age", "120")
            response.addHeader("Access-Control-Allow-Headers", allowHeaders)
        }

        // 验证权限
        if (this.hasPermission(request)) {
            return true
        }

        throw BizException.AUTH_ERROR
    }

    /**
     * 是否有权限
     * @return
     */
    abstract fun hasPermission(request: HttpServletRequest): Boolean

    fun addAllowHeaders(allowHeaders: String) {
        this.allowHeaders = allowHeaders
    }

    fun addExposeHeaders(exposeHeaders: String) {
        this.exposeHeaders = exposeHeaders
    }
}